package com.resys.server.aspect;
import com.resys.annotation.GlobalInterceptor;
import com.resys.entity.dto.TokenCustomerDto;
import com.resys.entity.dto.TokenUserInfoDto;
import com.resys.exception.BusinessException;
import com.resys.redis.RedisUtils;
import com.resys.server.component.RedisComponent;
import com.resys.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class GlobalOperactionAspect {
    @Resource
    private RedisComponent redisComponent;
    @Before("@annotation(com.resys.annotation.GlobalInterceptor)")
    public void interceptoDo(JoinPoint joinPoint){

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        GlobalInterceptor globalInterceptor = method.getAnnotation(GlobalInterceptor.class);
        if(globalInterceptor == null ){
            return;
        }
        if(globalInterceptor.checkLogin()){
            checkLogin();
        }
        return;
    }

    private void checkLogin() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = getTokenFromCookie(request);
        if(token == null || StringTools.isEmpty(token)){
            throw new BusinessException("请先登录");
        }
        TokenCustomerDto tokenCustomerDto = redisComponent.getTokenInfo4Cilent(token);
        if(tokenCustomerDto == null){
            throw new BusinessException("请先登录");
        }
    }
    private String getTokenFromCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            return null;
        }
        String token = null;
        for(Cookie cookie : cookies) {
            if(cookie.getName().equals("tokencustomer")) {
                return cookie.getValue();
            }
        }
        return null;

    }


}
